package com.freeLearning.boot.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.freeLearning.boot.common.result.Result;
import com.freeLearning.boot.core.security.util.SecurityUtils;
import com.freeLearning.boot.course.mapper.CounselLogMapper;
import com.freeLearning.boot.course.model.entity.CounselLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@Tag(name = "29.记录用户咨询日志")
@RequestMapping("/api/v1/counsel/log")
@RestController
@RequiredArgsConstructor
public class CounselLogController {
    private final CounselLogMapper counselLogMapper;

    @Operation(summary = "新增用户咨询日志")
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody CounselLog counselLog) {
        Long userId = SecurityUtils.getUserId();
        counselLog.setUserId(userId);
        counselLog.setCounselTime(LocalDateTime.now());
        // 判断今天是否已经咨询过
        CounselLog hasNowDayLog = counselLogMapper.selectOne(new LambdaQueryWrapper<CounselLog>()
                .eq(CounselLog::getConsultantId, counselLog.getConsultantId())
                .eq(CounselLog::getUserId, userId)
                .between(CounselLog::getCounselTime,
                        LocalDateTime.now().toLocalDate().atStartOfDay(),
                        LocalDateTime.now().toLocalDate().atTime(23, 59, 59))
        );
        if (hasNowDayLog != null){
            return Result.success(counselLogMapper.update(new LambdaUpdateWrapper<CounselLog>()
                    .eq(CounselLog::getConsultantId, counselLog.getConsultantId())
                    .eq(CounselLog::getUserId, userId)
                    .between(CounselLog::getCounselTime,
                            LocalDateTime.now().toLocalDate().atStartOfDay(),
                            LocalDateTime.now().toLocalDate().atTime(23, 59, 59))
                    .set(CounselLog::getCounselTime, LocalDateTime.now())
            ) > 0);
        }
        return Result.success(counselLogMapper.insert(counselLog) > 0);
    }
}
